package com.neu.config;


import com.neu.filter.JwtAuthenticationTokenFilter;
import com.neu.filter.UsernamePasswordFilter;
import com.neu.handler.AccessDeniedHandlerImpl;
import com.neu.handler.LogoutSuccessHandlerImpl;
import com.neu.service.AuthenticationService;
import com.neu.utils.JwtUtils;
import com.neu.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;



@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class WebSecurityConfig {
    @Autowired//注入数据源，用于查询当前要登录的用户信息
    private UserDetailsService userDetailsService;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;
    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;
    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;
    @Autowired
    private AuthenticationService authenticationService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtUtils jwtUtils;
    @Value("${swpt.jwt.expiration}")
    private Long expiration;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.csrf().disable()// 禁用 CSRF
                .cors(AbstractHttpConfigurer::disable)// 禁用跨域
                .sessionManagement(sessionManagementCustomizer -> sessionManagementCustomizer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))// 设置为无状态会话 禁用session
                .authenticationManager(authenticationManager(authenticationConfiguration))// 注入认证管理器
                .authorizeHttpRequests(authorizeHttpRequestsCustomizer -> authorizeHttpRequestsCustomizer
                        .mvcMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                        .mvcMatchers("/auth/login").permitAll()
                        .mvcMatchers("/auth/register").permitAll()
                        .mvcMatchers("/auth/captcha").permitAll()
                        .mvcMatchers("/doc.html").permitAll()
                        .mvcMatchers("/captcha/**").permitAll()
                        .mvcMatchers("/swagger-resources/**").permitAll()
                        .mvcMatchers("/v3/**").permitAll()
                        .mvcMatchers("/webjars/**").permitAll()
                        .mvcMatchers( "/favicon.ico").permitAll()
                        .mvcMatchers( "/sse/**").permitAll()
                        .mvcMatchers( "/minio/upload").permitAll()

                        .anyRequest().authenticated())
                .exceptionHandling(exceptionHandlingCustomizer -> exceptionHandlingCustomizer
                        // 未认证用户访问资源/认证信息过期失效处理器
                        .authenticationEntryPoint(authenticationEntryPoint)
                        // 权限不足处理器
                        .accessDeniedHandler(accessDeniedHandler)
                )
                .addFilterAt(usernamePasswordFilter(authenticationManager(authenticationConfiguration),redisUtil,jwtUtils,authenticationService), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new JwtAuthenticationTokenFilter(redisUtil,jwtUtils,expiration), UsernamePasswordAuthenticationFilter.class)
                .formLogin().disable() // 禁用默认的表单登录
                .logout(logoutCustomizer -> logoutCustomizer
                        .logoutUrl("/auth/logout")
                        .logoutSuccessHandler(logoutSuccessHandler)
                )
                .build();
    }

    // 注入 AuthenticationManager 认证管理器 注入自定义数据源和加密方式
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return new ProviderManager(daoAuthenticationProvider);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public UsernamePasswordFilter usernamePasswordFilter(AuthenticationManager authenticationManager, RedisUtil redisUtil, JwtUtils jwtUtils, AuthenticationService authenticationService) {
        return new UsernamePasswordFilter(authenticationManager, redisUtil, jwtUtils, authenticationService);
    }

}